package com.geline.sqlbackup.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.geline.sqlbackup.config.DatabaseBean;
import com.geline.sqlbackup.config.DatabaseItem;
import com.geline.sqlbackup.config.SqlBackupProperties;
import com.geline.sqlbackup.util.JdbcParseUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 神通数据库备份service
 *
 * @author: mengxin
 * @date: 2023/12/7 14:20
 */
@Slf4j
public class ShenTongBackupService {

    private SqlBackupProperties properties;

    public ShenTongBackupService(SqlBackupProperties properties){
        this.properties = properties;
    }

    public void start() {
        List<DatabaseBean> list = this.properties.getList();
        if(list == null || list.size()==0){
            log.warn("can not find config >>> database-backup:list !!!");
            return;
        }

        String savePath = properties.getSavePath();
        Objects.requireNonNull(savePath, "can not find savePath!");
        //String cron = databaseBean.getCron();
        //Objects.requireNonNull(cron, "can not find cron!");

        String key = properties.getKey();
        String jdbcUrl = SpringUtil.getProperty(key + ".url");
        String ipHost = JdbcParseUtils.findIpPortByUrl(jdbcUrl);
        String catalog = JdbcParseUtils.findCatalogByUrl(jdbcUrl);
        if(!savePath.endsWith("/")){
            savePath = savePath+"/";
        }
        DatabaseItem databaseItem = new DatabaseItem();
        databaseItem.setSavePath(savePath);
        databaseItem.setUsername(SpringUtil.getProperty(key + ".username"));
        databaseItem.setPassword(SpringUtil.getProperty(key + ".password"));
        this.backup(databaseItem, ipHost, catalog);
        //log.info("success to addTask dbName={}, cron = {}", dbName, cron);

        // 支持秒级别定时任务 CronUtil.setMatchSecond(true);
        /*if(!CronUtil.getScheduler().isStarted()){
            CronUtil.start();
        }*/
        log.info("CMD [备份神通数据库]！");
    }

    public boolean backup(DatabaseItem databaseItem, String hostIP, String dbName) {
        String fileName = String.format("%s%s_%s_%s.sql", databaseItem.getSavePath(), dbName, DateUtil.format(new Date(), "yyyyMMdd"), RandomUtil.randomString(4));
        log.info("fileName = {}", fileName);
        String cmd = String.format("mysqldump -opt -h %s -u %s -p %s -lock-all-tables=true -result-file=%s -default-character-set=utf8 %s",
                hostIP, databaseItem.getUsername(), databaseItem.getPassword(), fileName, dbName);
        log.info("cmd >>>> {}", cmd);
        try {
            Process process = Runtime.getRuntime().exec(cmd);
            if (process.waitFor() == 0) {// 0 表示线程正常终止。
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return false;
    }
}
